package com.whmskj.xjlhsc.mobie.energymanage.controller;

import com.github.pagehelper.PageHelper;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.core.Page;
import com.whmskj.xjlhsc.mobie.energymanage.service.MobileEnergyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.Collator;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@Api(tags = "移动端-能耗管理")
@RestController("mobileEnergyController")
@RequestMapping("/mobile/energy")
public class MobileEnergyController {
    @Resource
    private MobileEnergyService energyService;

    /**
     * 获取设备能耗概览列表，包含本日、本月、总能耗及实时数据
     * 可按日期和工序筛选
     *
     * @param day     日期，默认为当前日期
     * @param process 工序，可选
     * @return 设备能耗概览列表
     */
    @ApiOperation(value = "能耗概览（分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "day", value = "查询日期，格式：yyyy-MM-dd", required = false, paramType = "query"),
            @ApiImplicitParam(name = "process", value = "工序筛选", required = false, paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "页码(默认1)", required = false, paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页数量(默认10)", required = false, paramType = "query"),
            @ApiImplicitParam(name = "body", value = "可选JSON：{pageNum:1,pageSize:10}", required = false, paramType = "body")
    })
    @PostMapping("/overview")
    public AjaxResult overview(
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate day,
            @RequestParam(required = false) String process,
            @RequestParam(required = false) Integer pageNum,
            @RequestParam(required = false) Integer pageSize,
            @RequestBody(required = false) Map<String, Object> body) {
        if (body != null) {
            if (pageNum == null) {
                Object pn = body.get("pageNum");
                if (pn instanceof Number) pageNum = ((Number) pn).intValue();
                else if (pn instanceof String && !((String) pn).isEmpty()) {
                    try {
                        pageNum = Integer.parseInt((String) pn);
                    } catch (Exception ignored) {
                    }
                }
            }
            if (pageSize == null) {
                Object ps = body.get("pageSize");
                if (ps instanceof Number) pageSize = ((Number) ps).intValue();
                else if (ps instanceof String && !((String) ps).isEmpty()) {
                    try {
                        pageSize = Integer.parseInt((String) ps);
                    } catch (Exception ignored) {
                    }
                }
            }
            if (day == null && body.get("day") instanceof String) {
                day = LocalDate.parse((String) body.get("day"));
            }
            if ((process == null || process.isEmpty()) && body.get("process") instanceof String) {
                process = (String) body.get("process");
            }
        }
        PageHelper.startPage(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        List<Map<String, Object>> list = energyService.overview(day, process);
        // 按 deviceName 做“自然数”升序
        if (list != null && !list.isEmpty()) {
            final Collator collator = Collator.getInstance(Locale.CHINA);
            list.sort(
                    Comparator
                            .comparing((Map<String, Object> m) -> parseName(m).prefix, collator)
                            .thenComparingInt(m -> parseName(m).num)
                            .thenComparing(m -> String.valueOf(m.getOrDefault("deviceName", "")), collator)
            );
        }
        return Page.getDataTable(list);
    }

    /**
     * 解析设备名，提取中文前缀与尾随数字，以支持“自然数排序”。
     */
    private static NameParts parseName(Map<String, Object> row) {
        String name = row == null || row.get("deviceName") == null ? "" : String.valueOf(row.get("deviceName"));
        // 匹配前缀+数字
        java.util.regex.Matcher m = java.util.regex.Pattern.compile("^(\\D*?)(\\d+)$").matcher(name.trim());
        if (m.find()) {
            String prefix = m.group(1);
            int num;
            try { num = Integer.parseInt(m.group(2)); } catch (Exception ignored) { num = Integer.MAX_VALUE; }
            return new NameParts(prefix, num);
        }
        return new NameParts(name, Integer.MAX_VALUE);
    }

    private static final class NameParts {
        final String prefix;
        final int num;
        NameParts(String prefix, int num) { this.prefix = prefix == null ? "" : prefix; this.num = num; }
    }

    /**
     * 获取单个设备的能耗详情，包括日能耗曲线、月能耗曲线、实时数据和电能数据汇总
     *
     * @param deviceId 设备ID
     * @return 设备能耗详情
     */
    @ApiOperation(value = "设备能耗详情", notes = "包含日/月能耗曲线、实时数据与电能汇总")
    @ApiImplicitParam(name = "deviceId", value = "设备ID", required = true, paramType = "path")
    @GetMapping("/{deviceId}/detail")
    public AjaxResult detail(@PathVariable Long deviceId) {
        Map<String,Object> data = energyService.deviceDetail(deviceId);
        // 对 realtime.last7Days 的 day做降序
        if (data != null) {
            Object rt = data.get("realtime");
            if (rt instanceof Map) {
                Object last7Days = ((Map<?,?>) rt).get("last7Days");
                if (last7Days instanceof List) {
                    @SuppressWarnings("unchecked")
                    List<Map<String,Object>> items = (List<Map<String,Object>>) last7Days;
                    if (!items.isEmpty()) {
                        items.sort(Comparator.comparing(MobileEnergyController::parseDay).reversed());
                    }
                }
            }
        }
        return AjaxResult.success(data);
    }

    // 解析 day 字段（yyyy-MM-dd）；失败返回 LocalDate.MIN
    private static LocalDate parseDay(Map<String,Object> row) {
        if (row == null) return LocalDate.MIN;
        Object v = row.get("day");
        if (v == null) return LocalDate.MIN;
        try { return LocalDate.parse(String.valueOf(v).trim()); }
        catch (Exception ignored) { return LocalDate.MIN; }
    }

    /**
     * 获取所有工序列表
     *
     * @return 工序列表
     */
    @GetMapping("/processes")
    public AjaxResult processes() {
        return AjaxResult.success(energyService.processes());
    }

    /**
     * 统计设备采集状态（返回 {"Y":"N","N":"M"}）
     *
     * @param process 可选工序筛选，例如：细纱/清花
     */
    @ApiOperation("获取设备采集状态统计（支持工序筛选）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "process", value = "工序筛选", required = false, paramType = "query")
    })
    @GetMapping("/collection/stats")
    public AjaxResult getCollectionStatusStats(@RequestParam(required = false) String process) {
        // 使用新的查询逻辑，但保持原有返回格式
        java.util.List<java.util.Map<String,Object>> items = energyService.getCollectionStatusStats(process);
        long ok = 0L, down = 0L;
        if (items != null) {
            for (java.util.Map<String,Object> r : items) {
                Object f = r.get("collectFlag");
                Object c = r.get("count");
                int flag = (f instanceof Number) ? ((Number)f).intValue()
                        : (f != null ? Integer.parseInt(String.valueOf(f)) : 0);
                long cnt = (c instanceof Number) ? ((Number)c).longValue()
                        : (c != null ? Long.parseLong(String.valueOf(c)) : 0L);
                if (flag == 1) ok = cnt; else down = cnt;
            }
        }
        java.util.Map<String,Object> result = new java.util.LinkedHashMap<>();
        result.put("Y", String.valueOf(ok));
        result.put("N", String.valueOf(down));
        return AjaxResult.success(java.util.Collections.singletonList(result));
    }

}

